package network.urlconnection;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ContentHandler;
import java.net.URLConnection;

public class EchoContentHandler extends ContentHandler{

	/**
	 * 读取服务器的一行数据，并将它转换成字符串类型
	 */
	@Override
	public Object getContent(URLConnection urlc) throws IOException {
		InputStream is = urlc.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		return br.readLine();
	}
	
	/**
	 * 将服务器发送的数据，尝试转化成Class[]数组中第一个类型，如果不成功，尝试第二个，依次类推
	 */
	@Override
	public Object getContent(URLConnection urlc, Class[] classes)
			throws IOException {
		InputStream is = urlc.getInputStream();
		for(int i = 0; i < classes.length; i++){
			if(classes[i] == InputStream.class)
				return is;
			else if(classes[i] == String.class)
				return getContent(urlc);
		}
		return null;
	}

}
